// 认证初始化插件 - 仅在浏览器环境中执行

// 从localStorage中获取认证信息
const getAuthFromStorage = () => {
  try {
    const token = localStorage.getItem('token')
    const userStr = localStorage.getItem('user')
    const user = userStr ? JSON.parse(userStr) : null
    
    return {
      token,
      user,
      isAuthenticated: !!token
    }
  } catch (e) {
    console.error('Failed to get auth from localStorage:', e)
    return {
      token: null,
      user: null,
      isAuthenticated: false
    }
  }
}

export default (context) => {
  // 只在浏览器环境中执行
  if (process.client) {
    // 在客户端初始化时，从localStorage加载认证信息
    const { token, user } = getAuthFromStorage()
    
    // 如果有token，更新store中的认证状态
    if (token) {
      context.store.commit('auth/SET_TOKEN', token)
      if (user) {
        context.store.commit('auth/SET_USER', user)
      }
    }
  }
}